package model.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import Hibernate.dao.Exam;
import Hibernate.dao.ExamDAO;
import Hibernate.dao.ExamieeDAO;
import Hibernate.dao.FinalScore;
import Hibernate.dao.FinalScoreDAO;
import Hibernate.dao.Score;
import Hibernate.dao.ScoreDAO;

public class ScoreService {
		Map<String,String> map;
		ScoreDAO scoreDao;
		ExamDAO examDao;
		FinalScoreDAO finalScoreDao;
		ExamieeDAO examieeDao;
		public static String basePath =ScoreService.class.getClassLoader().getResource("/")
				.getPath();
		
		//为考试设置打分范围和最高最低的差值限制
		final int MAXSCORE = 100;
		final int MIXSCORE = 0;
		final int DIFF = 10;
		
		public void setExamieeDao(ExamieeDAO examieeDao) {
			this.examieeDao = examieeDao;
		}

		public void setFinalScoreDao(FinalScoreDAO finalScoreDao) {
			this.finalScoreDao = finalScoreDao;
		}

		public void setExamDao(ExamDAO examDao) {
			this.examDao = examDao;
		}

		public void setScoreDao(ScoreDAO scoreDao){
			this.scoreDao = scoreDao;
		}
		
		//新增score数据，通过userInfo增加记录，设置firstScore，finalScore，scoreTime
		public String giveScore(String userInfo) {
			
			//System.out.print(userInfo); //test
			
			map = new HashMap<String,String>();
			try{
				Score tempScore = new Score();
				JSONObject juserInfo = JSONObject.fromObject(userInfo);
				//System.out.print(juserInfo); //test
				
				if(juserInfo.containsKey("userId")){		
					tempScore.setUserId(juserInfo.getString("userId"));
					if(juserInfo.containsKey("expertId")){
						tempScore.setExpertId(juserInfo.getString("expertId"));
						if(juserInfo.containsKey("examId")){
							tempScore.setExamId(juserInfo.getString("examId"));
							if(juserInfo.containsKey("firstScore")&&Integer.parseInt(juserInfo.getString("firstScore"))>=MIXSCORE && Integer.parseInt(juserInfo.getString("firstScore"))<=MAXSCORE){
								tempScore.setFirstScore(juserInfo.getString("firstScore"));
								tempScore.setFinalScore("-1");
								if(juserInfo.containsKey("scoreTime")){
									tempScore.setScoreTime(juserInfo.getString("scoreTime"));
									scoreDao.save(tempScore); //Update数据库
									map.put("flag", "true");
								}else{
									map.put("flag", "false");
									map.put("reason", "打分时间不能为空");
								}
							}else{
								map.put("flag", "false");
								map.put("reason", "印象分不能为空且在0~100以内");
							}
						}else{
							map.put("flag", "false");
							map.put("reason", "考试id不能为空");
						}
					}else{
						map.put("flag", "false");
						map.put("reason", "专家id不能为空");
					}
				}else{
					map.put("flag", "false");
					map.put("reason", "考生号不能为空");
				}
					
			}catch(JSONException e){
				map.put("flag", "false");
				map.put("reason", "数据格式不正确");
				System.out.print(e.getMessage());
			}
		
			return JSONObject.fromObject(map).toString();
		}

		public void saveAverage(JSONObject juserInfo){
			boolean isOver = false;
			double finalAverage = 0;
			double firstAverage = 0;
			List list = scoreDao.findByUserId(juserInfo.getString("userId"));
			Exam tempExam = examDao.findById(juserInfo.getString("examId"));
			if(list.size()==tempExam.getExpertCount()){
				for(int i=0;i<list.size();i++){
					Score tempScore = (Score) list.get(i);
					if(tempScore.getFinalScore().equals("-1")){
						isOver = false;
						break;
					}else{
						isOver = true;
						firstAverage = firstAverage + Double.valueOf(tempScore.getFirstScore());
						finalAverage = finalAverage + Double.valueOf(tempScore.getFinalScore());
					}
				}
				if(isOver){
					firstAverage = firstAverage/list.size();
					finalAverage = finalAverage/list.size();
					FinalScore tempFinalScore = new FinalScore();
					tempFinalScore.setExamId(juserInfo.getString("examId"));
					tempFinalScore.setUserId(juserInfo.getString("userId"));
					tempFinalScore.setFirstScore(firstAverage);
					tempFinalScore.setFinalScore(finalAverage);
					finalScoreDao.save(tempFinalScore);
				}
			}
		} 
		
		public String giveSecScore(String userInfo) {
			// TODO Auto-generated method stub
			map = new HashMap<String,String>();
			try{
				JSONObject juserInfo = JSONObject.fromObject(userInfo);
				if(juserInfo.containsKey("userId")&&juserInfo.containsKey("expertId")&&juserInfo.containsKey("finalScore")&&juserInfo.containsKey("examId")){
					List list = scoreDao.findByUserIdExpertId(juserInfo.getString("userId"), juserInfo.getString("expertId"));
					if(list.size()==0){
						map.put("flag","false");
						map.put("reason", "没有找到数据");
					}else if(list.size()==1){
						Score tempScore = (Score) list.get(0);
						if(Integer.parseInt(juserInfo.getString("finalScore"))>=MIXSCORE && Integer.parseInt(juserInfo.getString("finalScore"))<=MAXSCORE){
							if(Math.abs(Integer.parseInt(tempScore.getFirstScore())-Integer.parseInt(juserInfo.getString("finalScore"))) <= DIFF){
								tempScore.setFinalScore(juserInfo.getString("finalScore"));
								scoreDao.attachDirty(tempScore);
								saveAverage(juserInfo);
								map.put("flag","true");
							}else{
								map.put("flag","false");
								map.put("reason", "与印象分不得相差过大");
							}
						}else{
							map.put("flag","false");
							map.put("reason", "最终分请在打分范围之间");
						}
					}else{
						map.put("flag","false");
						map.put("reason", "服务器错误");
					}
				}else{
					map.put("flag","false");
					map.put("reason", "数据为空");
				}
			}catch (JSONException e){
				map.put("flag", "false");
				map.put("reason", "数据格式不正确");
			}
			return JSONObject.fromObject(map).toString();
		}

		public String findFirstScore(String userExpertInfo) {
			// TODO Auto-generated method stub
			map = new HashMap<String,String>();
			try{
				JSONObject juserInfo = JSONObject.fromObject(userExpertInfo);
				if(juserInfo.containsKey("expertId")){
					JSONArray firstScoreJson = new JSONArray();
					List list = scoreDao.findByExpertId(juserInfo.getString("expertId"));
					//System.out.print(juserInfo.getString("expertId"));
					if(list.size()==0){
						map.put("flag","false");
						map.put("reason", "没有找到数据");
					}else {
						for(int i=0;i<list.size();i++){
							Score tempScore = (Score) list.get(i);
							JSONObject jsonObject = new JSONObject();
							jsonObject.put("firstScore", tempScore.getFirstScore());
							//System.out.print("houtai_firstscore:"+tempScore.getFirstScore());
							jsonObject.put("userName", examieeDao.findById(tempScore.getUserId()).getUserName().toString());
							jsonObject.put("admitId", examieeDao.findById(tempScore.getUserId()).getAdmitId().toString());
							firstScoreJson.add(jsonObject);
						}
						map.put("flag", "true");
						map.put("data", firstScoreJson.toString());
					}
				}else{
					map.put("flag","false");
					map.put("reason", "数据为空");
				}
			}catch (JSONException e){
				map.put("flag", "false");
				map.put("reason", "数据格式不正确");
			}
			return JSONObject.fromObject(map).toString();
		}

		public String scoreAll() {
			map = new HashMap<String,String>();
			JSONArray scoreJson = new JSONArray();
			List list = scoreDao.findAll();
			for(int i=0;i<list.size();i++){
				Score tempScore = (Score) list.get(i);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("userId",tempScore.getUserId());
				jsonObject.put("exprtId",tempScore.getExpertId());
				jsonObject.put("examId",tempScore.getExamId());
				jsonObject.put("firstScore",tempScore.getFirstScore());
				jsonObject.put("finalScore",tempScore.getFinalScore());
				jsonObject.put("scoreTime",tempScore.getScoreTime());
				scoreJson.add(jsonObject);
			}
			map.put("flag","true");
			map.put("data", scoreJson.toString());

			return JSONObject.fromObject(map).toString();
		}
		
		


		

		public InputStream ScoreToExcel(String path, String userInfo){
			String[] finalScoreInfo = userInfo.split("#");
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("FinalScore");
			List list = finalScoreDao.findAll();
			Object[][] value = new Object[list.size() + 1][finalScoreInfo.length];
			for (int m = 0; m < finalScoreInfo.length; m++) {
				value[0][m] = finalScoreInfo[m];
			}
			for (int i = 0; i < list.size(); i++) {
				FinalScore finalScore = (FinalScore) list.get(i);
				ArrayList<String> arrayList = finalScore.getInfo(finalScoreInfo);
				for (int j = 0; j < finalScoreInfo.length; j++) {
					value[i + 1][j] = arrayList.get(j);
				}
			}
			ExcelUtil.writeArrayToExcel(wb, sheet, list.size() + 1, finalScoreInfo.length,
					value);

			// ExcelUtil.writeWorkbook(wb, path);

			return getInputStream(wb, path);
		}
		
		public InputStream getInputStream(HSSFWorkbook wb, String path) {
			FileOutputStream fos = null;
			FileInputStream in = null;
			File f = new File(path);
			try {
				fos = new FileOutputStream(f);
				wb.write(fos);
				in = new FileInputStream(new File(path));
				wb.close();
				return in;
				// ByteArrayInputStream in = new ByteArrayInputStream( fos.)
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		

}
